<template>
    <div class="express-assignment">
        <div v-show="isShow" style="position: fixed;top: 0px;left: 0px;z-index:50000;width: 100%;height: 100%;background-color: rgba(0,0,0,0.3)">
            <van-loading type="spinner" color="white"  style="margin: 48vh auto 0;"/>
        </div>
        <div>
            <div class="order-list">
                <div>要指派的运单号</div>
                <ul id="full_dingdong-list" style="overflow:hidden;">
                    <li class="list-ddid" v-for="(item,index) in expressDetailData" :key="index">
                        <span style="position: relative;left: -0.12rem">{{item.full_dingdong}}</span>
                        <van-icon name="cross" @click="cancelOrder(item.id,item)" style="position: absolute;top: 0rem;right:0.05rem;opacity: 0.5;background-color: #eee;border-radius: 50%"/>
                    </li>
                </ul>
            </div>
            <express-assign
                    v-model="dataObj"
                    :datalist="datalist"
                    :datalistNext="datalistNext"
                    :option="siteOption"
                    :cascaderOption="cascaderOption">
            </express-assign>

            <div class="dialog-footer">
                <van-button type="default" @click="closePopup">取消</van-button>
                <van-button type="primary" @click="submitOrder">提交</van-button>
            </div>
        </div>

    </div>

</template>

<script>
    import Vue from 'vue';
    import ExpressAssign from './expressAssign/assign/ExpressAssign.vue';
    import {Notify, Button, Row, Col, Icon, Toast, Loading, Dialog } from 'vant';
    export default {
        name: 'express-assignment',
        components: {
            ExpressAssign,
            [Notify.name]:Notify,
            [Button.name]:Button,
            [Row.name]:Row,
            [Loading.name]:Loading,
            [Dialog.name]:Dialog,
            [Toast.name]:Toast,
            [Icon.name]:Icon,
            [Col.name]:Col
        },
        props: {
            value: {
                type: Object,
                default: ()=>{
                    return {}
                }
            }
        },
        data() {
            return {
                isShow: true,
                myValue: false,
                datalist: [
                    {name: '取件', label: 'pick_up', status: true},
                    {name: '中转取', label: 'go_spot_pick', status: true},
                    {name: '中转送', label: 'go_spot_send', status: true},
                    {name: '派件', label: 'send_to_send', status: true},
                    {name: '调度', label: 'go_point', status: false}
                ],
                datalistNext: [
                    {name: '取件', label: 'pick_up', status: false},
                    {name: '中转送', label: 'go_spot_send', status: true},
                    {name: '派件', label: 'send_to_send', status: true},
                    {name: '调度', label: 'go_point', status: false},
                    {name: '无', label: 'go_null', status: true}
                ],
                expressDetailData: [],
                driverData: [],
                cascaderOption: [],
                siteOption: [],
                siteApi: 'express/spot?pageSize=200', // 站点api
                driverApi: 'common/user/driver', // 站点api
                dataObj: {
                    driver_id: null,
                    order_ids: [],
                    mission: {
                        target: {   // 主任务
                            type: "pick_up", // 取件
                            spot_id: null,  //站点
                            driver_id: null,  //不传就是站长
                            address: null,
                            lat: null,
                            lon: null,
                        },
                        limit_time: "",
                        comment: "",
                        priority: 300,
                    },
                    next: {
                        target: {
                            type: "go_spot_send", // 中转
                            spot_id: null,  //站点
                            driver_id: null,  //不传就是站长
                            address: null,
                            lat: null,
                            lon: null
                        },
                        limit_time: "",
                        comment: "",
                        priority: 300
                    },

                },
                statusList: [
                    {
                        orderStatus: 1,
                        type: ['pick_up']
                    },
                    {
                        orderStatus: 5,
                        type: ['go_spot_send', 'send_to_send']
                    },
                    {
                        orderStatus: 7,
                        type: ['go_spot_pick']
                    },
                    {
                        orderStatus: 10,
                        type: ['go_spot_send', 'send_to_send']
                    },
                    {
                        orderStatus: 15,
                        type: ['go_spot_pick']
                    },
                    {
                        orderStatus: 20,
                        type: ['go_spot_send', 'send_to_send']
                    }
                ],
                driverTreeApi: 'user/driver/tree', // 司机api

            }
        },
        watch: {
            value: {
                handler() {
                    this.myValue = this.value;
                },
                deep:true
            },
            myValue: {
                handler(value) {
                    this.$emit('input', value);
                },
                deep: true
            }
        },
        mounted() {
            this.myValue = this.value;
            if (this.myValue.checkboxModel) {
                // this.getDriverData();
                this.getNowDate();
                this.init();
            }
        },
        methods: {
            cancelOrder(id,item) {
                this.$emit('changeAll');
                if (this.expressDetailData && this.expressDetailData.length == 1) {
                    Dialog.confirm({
                        title:'最后一项',
                        message: `<div style="text-align: center">确定取消叮咚码为<span style="color: red">${item.full_dingdong}</span></div>
                                <div  style="text-align: center">运单状态为<span  style="color: red">${item.status_link}</span>的运单？</div>
                                <div style="text-align: center">如果删除则自动关闭此页面,重新选择运单指派!</div>`
                    }).then(() => {
                        this.expressDetailData = [];
                        this.myValue.checkboxModel = [];
                        this.myValue.showPopup = false;
                    }).catch(() => {
                    });
                } else {
                    Dialog.confirm({
                        title:'谨慎操作',
                        message: `<div  style="text-align: center">确定取消叮咚码为<span style="color: red">${item.full_dingdong}</span></div>
                                <div  style="text-align: center">运单状态为<span  style="color: red">${item.status_link}</span>的运单？</div>`
                    }).then(() => {
                        this.expressDetailData.forEach((item,index)=>{
                            if (item.id == id) {
                                this.expressDetailData.splice(index,1);
                            }
                        });
                        this.myValue.checkboxModel.forEach((item,index)=>{
                            if (item == id) {
                                this.myValue.checkboxModel.splice(index,1);
                            }
                        });
                    }).catch(() => {
                    });
                }

            },
            init() {
                this.isShow = true;
                let getDriverTreeData = new Promise((resolve) => {
                    this.$http.get(this.driverTreeApi)
                        .then((response) => {
                            resolve(response)
                        }).catch((err)=>{
                            resolve(err)
                        })

                });
                let getPoint = new Promise((resolve) => {
                    this.$http.get(this.siteApi)
                        .then((response) => {
                            resolve(response)
                        }).catch((err)=>{
                        resolve(err)
                    })

                });
                let api = 'home/express/order?size=1&pageSize=' + this.myValue.checkboxModel.length + '&id$=[' + this.myValue.checkboxModel + ']';
                let getExpressDetail = new Promise((resolve) => {
                    this.$http.get(api)
                        .then((response) => {
                            resolve(response)
                        }).catch((err)=>{
                        console.info('err',err);
                            resolve(err)
                    })

                });
                Promise.all([getDriverTreeData,getPoint,getExpressDetail])
                    .then((res)=>{
                        this.isShow = false;
                        this.getDriverTreeData(res[0]);
                        this.getPoint(res[1]);
                        this.getExpressDetail(res[2]);

                    });
            },
            closePopup() {
                this.myValue.showPopup = false;
            },
            getDriverTreeData(response) {
                if (response.response) {
                    if (response.response.data.msg) {
                        this.$notify({
                            message: response.response.data.msg,
                            duration: 1000,
                            background: '#f44'
                        });
                    } else {
                        this.$notify({
                            message: '请求错误：' + response.response.status,
                            duration: 1000,
                            background: '#f44'
                        });
                    }
                } else {
                    if (response.data.code == 200) {
                        this.cascaderOption = response.data.data;
                    }

                }
            },
            getPoint(response) {
                if (response.response) {
                    if (response.response.data.msg) {
                        this.$notify({
                            message: response.response.data.msg,
                            duration: 1000,
                            background: '#f44'
                        });
                    } else {
                        this.$notify({
                            message: '请求错误：' + response.response.status,
                            duration: 1000,
                            background: '#f44'
                        });
                    }
                } else {
                    if (response.data.code == 200) {
                        this.siteOption = response.data.data;
                    }

                }
            },
            getExpressDetail(response) {
                if (response.response) {
                    if (response.response.data.msg) {
                        this.$notify({
                            message: response.response.data.msg,
                            duration: 1000,
                            background: '#f44'
                        });
                    } else {
                        this.$notify({
                            message: '请求错误：' + response.response.status,
                            duration: 1000,
                            background: '#f44'
                        });
                    }
                } else {
                    if (response.data.code == 200) {
                        this.expressDetailData = response.data.data;
                        this.judgeState(this.expressDetailData[0].order_status);
                    }

                }

            },
            // getDriverTreeData() {
            //     this.$http.get(this.driverTreeApi)
            //         .then((response) => {
            //             this.cascaderOption = response.data.data;
            //         })
            //         .catch((error) => {
            //             if (error.response.data.msg) {
            //                 this.$notify({
            //                     message: error.response.data.msg,
            //                     duration: 1000,
            //                     background: '#f44'
            //                 });
            //             } else {
            //                 this.$notify({
            //                     message: '请求错误：' + error.response.status,
            //                     duration: 1000,
            //                     background: '#f44'
            //                 });
            //             }
            //         });
            // },
            // getPoint() {
            //     this.$http.get(this.siteApi)
            //         .then((response) => {
            //             this.siteOption = response.data.data;
            //         })
            //         .catch((error) => {
            //             if (error.response.data.msg) {
            //                 this.$notify({
            //                     message: error.response.data.msg,
            //                     duration: 1000,
            //                     background: '#f44'
            //                 });
            //             } else {
            //                 this.$notify({
            //                     message: '请求错误：' + error.response.status,
            //                     duration: 1000,
            //                     background: '#f44'
            //                 });
            //             }
            //         });
            // },
            // getExpressDetail() {
            //     this.isShow = true;
            //     let self = this;
            //     let api = 'home/express/order?size=1&pageSize=' + this.paramsId.length + '&id$=[' + this.paramsId + ']';
            //     this.$http.get(api)
            //         .then((response) => {
            //             self.expressDetailData = response.data.data;
            //             self.judgeState(self.expressDetailData[0].order_status);
            //             self.isShow = false;
            //         })
            //         .catch((error) => {
            //             self.isShow = false;
            //             if (error.response.data.msg) {
            //                 self.$notify({
            //                     message: error.response.data.msg,
            //                     duration: 1000,
            //                     background: '#f44'
            //                 });
            //             } else {
            //                 self.$notify({
            //                     message: '请求错误：' + error.response.status,
            //                     duration: 1000,
            //                     background: '#f44'
            //                 });
            //             }
            //         });
            //
            // },
            getDriverData() {
                this.$http.get(this.driverApi)
                    .then((response) => {
                        this.driverData = response.data.data;
                    })
                    .catch((error) => {
                        if (error.response.data.msg) {
                            this.$notify({
                                message: error.response.data.msg,
                                duration: 1000,
                                background: '#f44'
                            });
                        } else {
                            this.$notify({
                                message: '请求错误：' + error.response.status,
                                duration: 1000,
                                background: '#f44'
                            });
                        }
                    });
            },
            setDataOne() {
                if (!this.dataObj.driver_id) {  // 取件必须指派司机
                    Toast.fail({
                        message:'司机未指派！',
                        duration: 1000
                    });
                    return false;
                }
                if (this.dataObj.next.target.type === 'send_to_send') {;
                    this.dataObj.next.target.spot_id = null; // 后置任务派送 无站点
                    this.dataObj.next.target.driver_id = null; // 后置任务派送 无接驳人
                }
                if (this.dataObj.next.target.type === 'go_spot_send') { //取件时后置任务时中转送 则必填站点
                    if (!this.dataObj.next.target.spot_id) {
                        Toast.fail({
                            message:'后置任务站点未选择！',
                            duration: 1000
                        });
                        return false;
                    }
                }
                this.dataObj.mission.target.spot_id = null; // 取件主任务  无站点
                this.dataObj.mission.target.address = null; // 取件主任务 调度地址
                this.dataObj.mission.target.lat = null; // 取件主任务 无经纬度
                this.dataObj.mission.target.lon = null; // 取件主任务 无经纬度
                this.dataObj.mission.target.driver_id = null; // 取件主任务 接驳人
                this.dataObj.next.target.address = null; // 取件后置任务 调度地址
                this.dataObj.next.target.lat = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.lon = null; // 取件后置任务 无经纬度
                return true;
            },
            setDataTwo() {
                if (!this.dataObj.mission.target.spot_id) {
                    Toast.fail({
                        message:'派送站点未指定！',
                        duration: 1000
                    });
                    return false;
                }
                this.dataObj.mission.driver_id = null;
                this.dataObj.mission.target.address = null; // 取件主任务 调度地址
                this.dataObj.mission.target.lat = null; // 取件主任务 无经纬度
                this.dataObj.mission.target.lon = null; // 取件主任务 无经纬度
                this.dataObj.next.target.address = null; // 取件后置任务 调度地址
                this.dataObj.next.target.lat = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.lon = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.driver_id = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.spot_id = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.type = null; // 取件后置任务 无经纬度
                return true;
            },
            setDataThree() {
                // if (!this.dataObj.driver_id) {  // 派件必须指派司机
                //     this.$message.error('司机未指派！');
                //     return false;
                // }
                this.dataObj.mission.target.spot_id = null;
                this.dataObj.mission.target.address = null; // 取件主任务 调度地址
                this.dataObj.mission.target.lat = null; // 取件主任务 无经纬度
                this.dataObj.mission.target.lon = null; // 取件主任务 无经纬度
                this.dataObj.next.target.address = null; // 取件后置任务 调度地址
                this.dataObj.next.target.type = null; // 取件后置任务 调度地址
                this.dataObj.next.target.lat = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.lon = null; // 取件后置任务 无经纬度
                this.dataObj.next.target.spot_id = null; // 取件后置任务 无经纬度
                return true;
            },
            postTask() {
                if (this.dataObj.mission.target.type === 'go_spot_pick' && this.dataObj.next.target.type === 'send_to_send') {
                    this.dataObj.mission.target.type = 'send_to_pick';
                }
                if (this.dataObj.next.target.type === 'go_null') {
                    this.dataObj.next.target.type = null;
                }
                this.isShow = true;
                this.$http.post('express/mission', this.dataObj)
                    .then((response) => {
                        this.isShow = false;
                        Toast.success({
                            message:'恭喜你，指派成功！',
                            duration: 1000
                        });
                        // this.$emit('input', false);
                        this.$emit('refreshList');
                    })
                    .catch((error) => {
                        this.isShow = false;
                        if (this.dataObj.mission.target.type === 'send_to_pick' && this.dataObj.next.target.type === 'send_to_send') {
                            this.dataObj.mission.target.type = 'go_spot_pick';
                        } // 如果主任务未中转取后置任务为派送 指派失败时恢复原状态
                        if (this.dataObj.next.target.type === null) {
                            this.dataObj.next.target.type = 'go_null';
                        }
                        if (error.response.data.msg) {
                            this.$notify({
                                message: error.response.data.msg,
                                duration: 1000,
                                background: '#f44'
                            });
                        } else {
                            this.$notify({
                                message: '请求错误：' + error.response.status,
                                duration: 1000,
                                background: '#f44'
                            });
                        }
                    });
            },
            submitOrder() {
                // this.dataObj.order_ids = this.paramsId.split(',');
                this.dataObj.order_ids = this.myValue.checkboxModel;
                if (this.dataObj.mission.target.type === 'pick_up' || this.dataObj.mission.target.type === 'go_spot_pick') {
                    if (!this.setDataOne()) {
                        return;
                    }
                } else if (this.dataObj.mission.target.type === 'go_spot_send') {
                    if (!this.setDataTwo()) {
                        return;
                    }
                } else if (this.dataObj.mission.target.type === 'send_to_send') {
                    if (!this.setDataThree()) {
                        return;
                    }
                }
                this.postTask()
            },
            getNowDate() {
                let date = new Date();
                let seperator1 = "-";
                let seperator2 = ":";
                let month = date.getMonth() + 1;
                let strDate = date.getDate();
                let strSeconds = date.getSeconds();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                if (strSeconds >= 0 && strSeconds <= 9) {
                    strSeconds = "0" + strSeconds;
                }
                date.setMinutes(date.getMinutes() + 30);
                let currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                    + " " + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + strSeconds;
                this.dataObj.mission.limit_time = currentdate;
                date.setMinutes(date.getMinutes() + 30);
                let currentdate1 = date.getFullYear() + seperator1 + month + seperator1 + strDate
                    + " " + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + strSeconds;
                this.dataObj.next.limit_time = currentdate1;
            },
            judgeState(status) {
                let self = this;
                for (let index in self.statusList) {
                    if (status === self.statusList[index].orderStatus) {
                        self.datalist.forEach(tab => {
                            if (self.statusList[index].type.join(',').indexOf(tab.label) !== -1) {

                                tab.status = true;
                                // self.dataObj.mission.target.type = self.statusList[index].type[0];
                            } else {
                                tab.status = false;
                            }
                        })
                        let target = self.dataObj.mission.target;
                        target.type = self.statusList[index].type[0];
                        Vue.set(self.dataObj.mission, 'target', target);
                    }
                }
                // console.info('状态', self.dataObj);
            } // 判断快件状态 限时快件按钮
        }
    }
</script>

<style lang="less">
    .express-assignment {
        /*padding-top: 0.11rem;*/
        height: 100%;
        background-color: #EAEAEA;
        padding: 0.11rem 0.1rem 0;
        /*position: relative;*/
       .order-list{
           width: 100%;
           margin: 0 auto;
           padding:0.11rem 0.16rem 0.11rem 0.11rem ;
           border-radius: 0.06rem;
           background-color: #fff;
           overflow: hidden;
           .list-ddid{
               position: relative;
               width: 50%;
               list-style: disc inside;
               float: left;
               color: #4A4A4A;
               margin-top: 0.04rem;
               font-size: 0.16rem;
           }

       }
        .dialog-footer{
            position: fixed;
            bottom: 0px;
            left: 0px;
            display: flex;
            justify-content: space-around;
            padding: 0.06rem 0;
            background-color: #fff;
            width: 100%;
            box-shadow: 0 2px 9px 0 rgba(0,0,0,0.43);
        }
        .van-button{
            width: 1.6rem;
        }
        .van-button--default{
            font-size: 0.18rem;
            color: #108EE9;
            border: 1px solid #108EE9;
            border-radius: 0.06rem;;
        }
        .van-button--primary{
            background: #108EE9;
            border-radius: 0.06rem;
            border: 1px solid #108EE9;
            font-size: 0.18rem;
            color: #FFFFFF;
        }

    }

</style>

